import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {
    Grid,
    Typography,
    colors,
    FormControl,
    OutlinedInput,
    InputAdornment,
    Tabs,
    Tab,
    Box,
} from '@material-ui/core';
import Pagination from '@material-ui/lab/Pagination';
import { Image, Icon } from 'components/atoms';
import cd from "assets/images/cd.png"
import { callGetNewsApi } from 'utils/networking';

import { useDispatch, useSelector } from 'react-redux'
import { Hero, Genres } from "../../components"
import { useHistory, useLocation } from 'react-router-dom/cjs/react-router-dom.min';

const useStyles = makeStyles(theme => ({
    root: {
        width: "100%",
        padding: "0 20px",
        background: '#000',
        marginTop: "-10px",
        "& .MuiTabs-indicator": {
            display: "none"
        },
        "& .MuiTab-root": {
            color: "white",
            paddingLeft: "25px",
            paddingRight: "25px",
        },
        "& .MuiTab-wrapper": {
            padding: "0 8px",
            borderRadius: "2px",
        },
        "& .Mui-selected .MuiTab-wrapper": {
            background: "#E24575",
        },
    },
    title: {
        textAlign: "center",
        fontFamily: "HurmeGeometricSans3-Black",
        fontSize: "56px",
        fontStyle: "normal",
        fontWeight: 700,
        lineHeight: "normal",
        color: "rgba(30, 30, 30, 1)",
        padding: "50px 0",
        [theme.breakpoints.up('md')]: {
            fontSize: "63px",
        },
    },
    typography: {
        fontFamily: "HurmeGeometricSans3-Black",
        fontSize: "40px",
        fontStyle: "normal",
        fontWeight: 700,
        lineHeight: "40px",
        textTransform: "uppercase",
        color: "#7E53F9",
        [theme.breakpoints.up('md')]: {
            fontSize: "80px",
            lineHeight: "85px",
        },
        textAlign: "center",
    },
    typography1: {
        color: "#fff",
    },
    typography2: {
        color: "#000",
        lineHeight: "normal",
        fontSize: "25px",
    },
    typography3: {
        fontSize: "16px",
        lineHeight: "normal",
        color: "#C6C6CA",
    },
    typography4: {
        fontSize: "16px",
        lineHeight: "normal",
        color: "#C6C6CA",
    },
    grid: {
        padding: "10px",
        cursor: "pointer",
    },
    gridItem: {
        padding: "10px",
    },
    searchTitle: {
        fontSize: "32px",
        lineHeight: "1.2",
        margin: "15px 0 30px 10px",
    },
    filter: {
        fontSize: "20px",
        color: "#E24575",
        margin: "10px 0 0 10px",
    },
    filterItem: {
        fontSize: "18px",
        color: "#B4B4B4",
        margin: "16px",
        cursor: "pointer",
        marginRight: "0",
        lineHeight: "32px",
    },
    select: {
        fontSize: "20px",
        color: "#E24575",
        margin: "20px 0 20px 35px",
    },
    selectItem: {
        fontSize: "16px",
        cursor: "pointer",
        lineHeight: "40px",
    },
    image: {
        // width: "250px",
        height: "250px",
        borderRadius: "8px",
        overflow: "hidden",
        [theme.breakpoints.up('md')]: {
            height: "250px",
        },
        [theme.breakpoints.up('md')]: {
            height: "200px",
        },
        [theme.breakpoints.up('lg')]: {
            height: "300px",
        },
    },
    img: {
        objectFit: "cover"
    },
    adImage: {
        borderRadius: "8px",
        overflow: "hidden",
        marginTop: "30px",
        display: "none",
        "& span": {
            verticalAlign: "middle",
        },
        [theme.breakpoints.up('md')]: {
            display: "block",
        },
    },
    adLeft: {
        marginRight: "50px"
    },
    adRight: {
        marginLeft: "50px"
    },
    medias: {
        minHeight: "50vh",
        [theme.breakpoints.up('md')]: {
            minHeight: "100vh",
        },
    },
    pagination: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        padding: "20px 0",
        "& .MuiPaginationItem-page": {
            backgroundColor: "#232637",
            color: "#FFFFFF",
        },
        "& .Mui-selected": {
            backgroundColor: "#E24575",
        },
        "& .MuiPaginationItem-ellipsis": {
            color: "#FFFFFF",
        },
    }
}));


const filterText = ["Picanha turducken", "Prosciutto frankfurter", "Ribeye sausage",]
const navText = ["Podcasts", "Episodes", "Season", "Albums", "Songs", "Artists", "Playlists",]

function Result() {

    const classes = useStyles();

    const [searchKey, setSearchKey] = useState('');

    const [discoverAllData, setDiscoverAllData] = useState({
        podcasts: { data: [] },
        songs: { data: [] },
        adv: {},
        playlists: { data: [] },
        albums: { data: [] },
        artists: { data: [] },
        episodes: { data: [] },
        season: { data: [] },
    });
    const [offset, setOffset] = useState(1);
    const [count, setCount] = useState(0);
    const selectId = useSelector((state) => state.liveFeed.selectId);

    const dispatch = useDispatch()
    const location = useLocation();
    const history = useHistory()
    // console.log(discoverAllData)

    const searchBlogs = () => {
        getServerSideProps()
    }

    const [currentTab, setCurrentTab] = useState(location.state ? location.state : 0);
    const handleTabChange = (event, newValue) => {
        setCurrentTab(newValue);
        setOffset(1)
    };

    useEffect(() => {
        getServerSideProps()
        setCount(discoverAllData[navText[currentTab].toLocaleLowerCase()]?.counts?.total_pages)
    }, [currentTab])

    function a11yProps(index) {
        return {
            id: `simple-tab-${index}`,
            'aria-controls': `simple-tabpanel-${index}`,
        };
    }

    function TabPanel(props) {
        const { children, value, index, ...other } = props;

        return (
            <div
                role="tabpanel"
                hidden={value !== index}
                id={`simple-tabpanel-${index}`}
                aria-labelledby={`simple-tab-${index}`}
                {...other}
            >
                {value === index && (
                    <Box sx={{ p: { xs: 0, sm: 3 } }}>
                        <Typography component={"div"}>{children}</Typography>
                    </Box>
                )}
            </div>
        );
    }

    TabPanel.propTypes = {
        children: PropTypes.node,
        index: PropTypes.number.isRequired,
        value: PropTypes.number.isRequired,
    };


    useEffect(() => {
        getServerSideProps()
    }, [searchKey, offset,selectId])

    const getServerSideProps = async () => {
        callGetNewsApi(`song/search_all_v1?search_text=${searchKey}&offset=${offset}&limit=16&genre_ids=${selectId.join(",")}`, dispatch, (data) => {
            console.log(data);
            setDiscoverAllData(data);
        })
    }

    const handlePagination = (_, value) => {
        setOffset(value)
    }
    const token = localStorage.getItem('token');

    return (
        <div className={classes.root} data-aos="fade-up">
            <Hero setSearchKey={setSearchKey} searchBlogs={searchBlogs} />
            <Grid container>
                <Grid item xs={12} sm={12} md={3}>
                    <div className={classes.itemContent}>
                        <Genres />
                        <div className={classes.adLeft}>
                            <div className={classes.adImage}>
                                <Image
                                    src={discoverAllData.adv.image_url ? discoverAllData.adv.image_url : ""}
                                    alt={"..."}
                                    srcSet={discoverAllData ? discoverAllData.adv.image_url : ""}
                                    lazyProps={{ width: '100%', height: '100%' }}
                                />
                            </div>
                        </div>
                    </div>
                </Grid>
                <Grid item xs={12} md={9}>
                    <Box sx={{ width: '100%' }}>
                        <Box sx={{ borderBottom: 1, borderColor: 'divider', mt: 4 }}>
                            <Tabs value={currentTab} onChange={handleTabChange} aria-label="basic tabs example" variant="scrollable"
                                scrollButtons="auto">
                                {
                                    navText.map((item, index) => (<Tab label={item} {...a11yProps(index)} key={index} />))
                                }
                            </Tabs>
                        </Box>
                        <TabPanel value={currentTab} index={0}>
                            <div className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.podcasts?.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        window.location.href = `/podcast/${item.id}`;
                                                    }}
                                                >

                                                    <Image
                                                        src={item?.avatarURL}
                                                        alt={item?.avatarURL}
                                                        srcSet={item?.avatarURL}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.title}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.host}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>
                        <TabPanel value={currentTab} index={1}>
                            <div id='media_container' className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.episodes.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        window.location.href = `${process.env.REACT_APP_SERVER_URL}player/episode/${item.id}/${token}`;
                                                    }}
                                                >
                                                    <Image
                                                        src={item?.avatarURL}
                                                        alt={item?.avatarURL}
                                                        srcSet={item?.avatarURL}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.name}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.podcastTitle}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>
                        <TabPanel value={currentTab} index={2}>
                            <div id='media_container' className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.season.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        window.location.href = `${process.env.REACT_APP_SERVER_URL}player/season/${item.id}/${token}`;
                                                    }}
                                                >
                                                    <Image
                                                        src={item?.avatarURL}
                                                        alt={item?.avatarURL}
                                                        srcSet={item?.avatarURL}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.name}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.podcastTitle}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>
                        <TabPanel value={currentTab} index={3}>
                            <div className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.albums.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        window.location.href = `${process.env.REACT_APP_SERVER_URL}player/album/${item.id}/${token}`;
                                                    }}
                                                >
                                                    <Image
                                                        src={item?.image}
                                                        alt={item?.image}
                                                        srcSet={item?.image}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.title}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.artistName}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>
                        <TabPanel value={currentTab} index={4}>
                            <div className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.songs.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        window.location.href = `${process.env.REACT_APP_SERVER_URL}player/play/${item.id}/${token}`;
                                                    }}
                                                >
                                                    <Image
                                                        src={item?.album_art}
                                                        alt={item?.album_art}
                                                        srcSet={item?.album_art}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.albumName}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.artistName}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>
                        <TabPanel value={currentTab} index={5}>
                            <div className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.artists.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        history.replace("/account/artist_profile",item)
                                                    }}

                                                >
                                                    <Image
                                                        src={item?.avatarURL}
                                                        alt={item?.avatarURL}
                                                        srcSet={item?.avatarURL}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.name}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.artistName}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>
                        <TabPanel value={currentTab} index={6}>
                            <div className={classes.medias} data-aos="fade-up">
                                <Grid container>
                                    {
                                        discoverAllData?.playlists.data.map((item, index) => (<Grid item xs={6} md={4} lg={3} container className={classes.grid} key={index}>
                                            <Grid item xs={12} >
                                                <div className={classes.image}
                                                    onClick={() => {
                                                        window.location.href = `${process.env.REACT_APP_SERVER_URL}player/playlist/${item.id}/${token}`;
                                                    }}
                                                >
                                                    <Image
                                                        src={item?.remoteAvatarPath}
                                                        alt={item?.remoteAvatarPath}
                                                        srcSet={item?.remoteAvatarPath}
                                                        lazyProps={{ width: '100%', height: '100%' }}
                                                        className={classes.img}
                                                    />
                                                </div>
                                            </Grid>
                                            <Grid item xs={12} className={classes.gridItem}>
                                                <Typography className={clsx(classes.typography, classes.typography3)}>{item.name}</Typography>
                                                <Typography className={clsx(classes.typography, classes.typography4)}>{item.artistName}</Typography>
                                            </Grid>
                                        </Grid>))
                                    }
                                </Grid>
                            </div>
                        </TabPanel>

                        <div className={classes.pagination}>
                            <Pagination count={count} variant="outlined" shape="rounded" onChange={handlePagination} />
                        </div>
                    </Box>
                </Grid>
            </Grid>
        </div>
    )
}

Result.propTypes = {
    /**
     * External classes
     */
    className: PropTypes.string,
};

export default Result

